import os
import socket


def client():
    # 设置连接IP地址
    IP_PORT = ('127.0.0.1', 9999)
    # 创建tcp套接字
    sk = socket.socket()
    # 与服务端建立连接
    sk.connect(IP_PORT)
    # os.path.dirname(__file__):获取当前文件的目录
    # os.path.abspath(__file__):获取绝对路径
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))

    print(BASE_DIR)
    while True:
        inp = input('>>>')
        print(inp)
        cmd, path = inp.split('|')
        print(cmd,path)
        # 路径拼接将分割路径拼接到原有路径
        path = os.path.join(BASE_DIR, path)
        print(path)
        # basename:获取文件目录最后一个
        file_name = os.path.basename(path)
        # 返回指定文件的大小并返回
        file_size = os.stat(path).st_size
        file_info = 'post|%s|%s' % (file_name, file_size)
        # 把文件路径转换成字节形式传递过去
        sk.sendall(bytes(file_info, "utf-8"))
        has_sent = 0
        with open(path, 'rb') as fp:
            while has_sent != file_size:
                data = fp.read(1024)
                sk.sendall(data)
                has_sent += len(data)
                print('\r' + '[上传进度]:%s%0.2f%%' % ('>' * int((has_sent / file_size) * 50),
                                                   float(has_sent / file_size) * 100), end='')

            print()
            print('%s 上传成功' % file_name)


if __name__ == '__main__':
    client()
